package dao;

import entity.User;
import util.DBUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDao {
    /**
     * 依据用户名查询，如果找不到，返回null,
     * 否则返回一个User对象
     *
     */
    public User login(User loginUser) {

        Connection con = null;
        PreparedStatement prs = null;
        ResultSet resultSet = null;
        User user = null;

        try {
            con = DBUtils.getConn();
            String sql = "select * from user where username=? and password=?";
            prs = con.prepareStatement(sql);
            prs.setString(1,loginUser.getUsername());
            prs.setString(2,loginUser.getPassword());

            resultSet = prs.executeQuery();

            if(resultSet.next()) {
                user = new User();
                //
                user.setId(resultSet.getInt("id"));
                user.setUsername(resultSet.getString("username"));
                user.setPassword(resultSet.getString("password"));
                user.setAge(resultSet.getInt("age"));
                user.setGender(resultSet.getString("gender"));
                user.setEmail(resultSet.getString("email"));
            }else{
                System.out.println("登录失败！");
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DBUtils.getClose(con,prs,resultSet);
        }
        return user;
    }

    public void register(User user) {
        Connection con = null;
        PreparedStatement prs = null;
        try {
            con = DBUtils.getConn();
            String sql = "insert into user(username,password,age,gender,email) values (?,?,?,?,?)";
            prs = con.prepareStatement(sql);
            prs.setString(1, user.getUsername());
            prs.setString(2, user.getPassword());
            prs.setInt(3, user.getAge());
            prs.setString(4, user.getGender());
            prs.setString(5, user.getEmail());
            int ret = prs.executeUpdate();
            if (ret == 1) {
                System.out.println("注册成功！");
            } else {
                System.out.println("注册失败！");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtils.getClose(con, prs, null);
        }
    }


/*    public static void main(String[] args) {
        User user = new User();
        user.setUsername("李四");
        user.setPassword("2222");
        user.setAge(12);
        user.setGender("女");
        user.setEmail("12356@qq.com");
        UserDao userDao = new UserDao();
        userDao.register(user);
    }*/
/*
    public static void main(String[] args) {
        User user = new User();
        user.setUsername("李四");
        user.setPassword("666");
        UserDao userDao = new UserDao();
        User user1 = userDao.login(user);
        System.out.println(user1);
    }*/


}
